package com.qingcloud.df.executor.utils;


import cn.hutool.core.io.IoUtil;
import io.minio.*;
import io.minio.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * minio文件上传工具类
 */
@Slf4j
@Service
public class MinioUtil {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${qingcloud.file-server.oss.region}")
    private String bucketName;
    @Resource
    private MinioClient minioClient;


    public ResponseEntity<byte[]> download(String objectName) throws Exception{
        return this.download(objectName, MediaType.APPLICATION_OCTET_STREAM);
    }

    public ResponseEntity<byte[]> download(String objectName, MediaType mediaType) throws  Exception{
        ResponseEntity<byte[]> responseEntity = null;
        InputStream inputstream = null;
        try {
            inputstream =  getMinioFile(objectName);
            // 封装返回值
            byte[] bytes = IoUtil.readBytes(inputstream);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(objectName, StandardCharsets.UTF_8));
            headers.setContentLength(bytes.length);
            headers.setContentType(mediaType);
            headers.setAccessControlExposeHeaders(List.of("*"));
            responseEntity = new ResponseEntity<>(bytes, headers, HttpStatus.OK);
            logger.debug("download file size : {}", bytes.length);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(inputstream != null) {
                try {
                    inputstream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return responseEntity;
    }


    /**
     * 获取文件流
     * @param objectName
     * @return
     */
    public InputStream getMinioFile(String objectName){
        return getMinioFile(bucketName,objectName);
    }
    /**
     * 获取文件流
     * @param bucketName
     * @param objectName
     * @return
     */
    public InputStream getMinioFile(String bucketName,String objectName){
        InputStream inputStream = null;
        try {
            GetObjectArgs objectArgs = GetObjectArgs.builder().object(objectName)
                    .bucket(bucketName).build();
            inputStream = minioClient.getObject(objectArgs);
        } catch (Exception e) {
            log.info("文件获取失败" + e.getMessage());
        }
        return inputStream;
    }
    /**
     * 获取文件外链
     * @param bucketName
     * @param objectName
     * @param expires
     * @return
     */
    public String getObjectUrl(String bucketName, String objectName, Integer expires) {
        if(bucketName==null || bucketName.equals(""))
            bucketName = this.bucketName;

        try{
            GetPresignedObjectUrlArgs objectArgs = GetPresignedObjectUrlArgs.builder().object(objectName)
                    .bucket(bucketName)
                    .expiry(expires).method(Method.GET).build();
            String url = minioClient.getPresignedObjectUrl(objectArgs);
            return URLDecoder.decode(url,"UTF-8");
        }catch (Exception e){
            log.info("文件路径获取失败" + e.getMessage());
        }
        return null;
    }

}
